﻿using System;
using System.Collections.Generic;
using System.Text;
using CommonLib.IDAL;
using CommonLib.Model;
using System.Data.SqlClient;

namespace MSSQLDAL
{
    public class TransactionDAL : IMyTransactionDAL
    {
        /// <summary>
        /// 开始事务，并返回事务对象

        /// </summary>
        /// <returns></returns>
        public CommonLib.Model.DBTransaction BeginTransaction()
        {
            CommonLib.Model.DBTransaction dbTrans = new CommonLib.Model.DBTransaction();
            try
            {
                //if (sql_conn != null)
                //{
                dbTrans.sql_conn= new SqlConnection(Conn.SqlConnStr);
                dbTrans.sql_conn.Open();
                dbTrans.sql_trans = dbTrans.sql_conn.BeginTransaction();
                //}
                return dbTrans;
            }
            catch (System.Exception e)
            {
                return null;
            }

        }

        /// <summary>
        /// 提交事务
        /// </summary>
        /// <param name="sql_trans"></param>
        /// <returns></returns>
        public int CommitTran(CommonLib.Model.DBTransaction dbTrans)
        {
            try
            {
                if (dbTrans.sql_trans != null)
                {
                    dbTrans.sql_trans.Commit();
                    dbTrans.sql_conn.Close();
                }
                return 0;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        /// <param name="sql_trans"></param>
        /// <returns></returns>
        public int RollBackTran(CommonLib.Model.DBTransaction dbTrans)
        {
            try
            {
                if (dbTrans.sql_trans != null)
                {
                    dbTrans.sql_trans.Rollback();
                    dbTrans.sql_conn.Close();
                }
                return 0;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
    }


}
